import React, {Component} from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import './index.less';
import {reqLogin} from "../../api/user";
import store from 'store';
import PropTypes from 'prop-types';

// 登录页表单
export default class LoginForm extends Component{
  static propTypes = {
    history: PropTypes.object.isRequired
  }

  state = {
    loading: false
  }

  onFinish = (values) => {
    this.loginClick(values);
  };

  loginClick = (data) => { // 点击登录
    this.setState({loading: true})
    reqLogin(data).then(res => {
      const {token, user} = res.data; // 设置token
      store.set('token', token);
      store.set('user', user);
      message.success('登录成功');
      this.setState({loading: false});
      this.props.history.replace('/admin', {user});
    }).catch(err => {
      message.error(err.data.message);
      this.setState({loading: false});
    })
  }

  render() {
    const {loading} = this.state;
    return (
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{
          remember: true,
        }}
        onFinish={this.onFinish}
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: '请输入用户名',
            },
            {
              type: 'string',
              len: 8,
              pattern: /^[0-9a-zA-Z_]{1,}$/,
              message: '用户名必须是8位字母、数字、_组成'
            }
          ]}
        >
          <Input size="large" prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
            {
              type: 'string',
              min: 6,
              max: 16,
              pattern: /^[0-9a-zA-Z]{1,}$/,
              message: '密码必须是6-16位字母、数字组成'
            }
          ]}
        >
          <Input
            size="large"
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" size="large" htmlType="submit" loading={loading}
                  className="login-form-button">
            登录
          </Button>
        </Form.Item>
      </Form>
    )
  }
}

